package com.zj.osm.view.homepage

import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.ZipUtils
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import com.zj.osm.R
import com.zj.osm.utils.ProgressDialogUtil
import com.zj.osm.utils.XmlUtils.xmlFileToStr
import com.zj.osm.utils.ZipUtil
import com.zj.utils.utils.ThreadManager
import com.zj.utils.utils.utilcode.Utils.runOnUiThread
import com.zj.utils.view.PopupList
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * @project OsmDroid
 * @author jiang zhu
 * @data 2019/12/6
 */
@Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class ZipAdapter (var context: Context, layoutId: Int, var rowsBeanList: ArrayList<File>) :
        CommonAdapter<File>(context, layoutId, rowsBeanList) {
    private val filePath = Environment.getExternalStorageDirectory().absolutePath  //根路径

    @RequiresApi(Build.VERSION_CODES.N)
    override fun convert(holder: ViewHolder?, t: File?, position: Int) {
        val zipItem = holder?.getView<RelativeLayout>(R.id.zipItem)
        val icon = holder?.getView<ImageView>(R.id.icon)
        val name = holder?.getView<TextView>(R.id.name)
        val time = holder?.getView<TextView>(R.id.desc)
        val lineOnClick = holder?.getView<RelativeLayout>(R.id.lineOnClick)
        val date = t?.lastModified()
        time?.text = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Date(date!!))
        icon?.setImageResource(R.drawable.zip)
        lineOnClick?.visibility = View.GONE
        name?.text = t.name
        zipItem?.setOnClickListener {
            importFile(t)
            //ToastUtils.showSho(t.name)
        }


        val popupList = PopupList(context)//长按弹出popupwindow
        popupList.bind(zipItem, listOf("路径", "导入", "删除"), object : PopupList.PopupListListener {
            override fun showPopupList(adapterView: View, contextView: View, contextPosition: Int): Boolean {
                return true
            }

            @RequiresApi(Build.VERSION_CODES.N)
            override fun onPopupListClick(contextView: View, contextPosition: Int, position: Int) {
                /*Toast.makeText(context, "$contextPosition,$position", Toast.LENGTH_SHORT).show()*/
                if (contextPosition == 0 && position == 2) {//删除
                    val dialog = NormalDialog(context)
                    dialog.content("您确定要删除${t.name}吗?")//
                            .style(NormalDialog.STYLE_TWO)//
                            .btnNum(2)
                            .title("删除提示")
                            .btnText("取消", "删除")//
                            .show()
                    dialog.setOnBtnClickL(OnBtnClickL {
                        dialog.dismiss()
                    }, OnBtnClickL {
                        if (FileUtils.deleteFile(t.absolutePath)) {
                            ToastUtils.showShort("删除成功")
                            dialog.dismiss()
                            //删除文件
                            rowsBeanList.remove(t)
                            notifyDataSetChanged()
                        } else {
                            ToastUtils.showShort("删除失败")
                        }
                    })
                } else if (contextPosition == 0 && position == 1) {//导入
                    importFile(t)
                } else {
                    ToastUtils.showShort(t.absolutePath)
                }
            }
        })
    }


    /**
     * 导入文件操作
     */
    @RequiresApi(Build.VERSION_CODES.N)
    private fun importFile(t: File?) {
        val dialog = NormalDialog(context)
        dialog.content("您确定要导入${t?.name}吗?")//
                .style(NormalDialog.STYLE_TWO)//
                .btnNum(2)
                .title("导入提示")
                .btnText("取消", "确定")//
                .show()
        dialog.setOnBtnClickL(OnBtnClickL {
            KeyboardUtils.hideSoftInput(context as Activity) //关闭软键盘
            dialog.dismiss()
        }, OnBtnClickL {
            KeyboardUtils.hideSoftInput(context as Activity) //关闭软键盘
            dialog.dismiss()
            Log.e("哈哈哈哈  ", t?.path + "    $filePath/bhne")
            val fileList = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //ZipUtils.unzipFile(t?.path, "$filePath/bhne")
                ZipUtil.unZipFolder(t!!.path, "$filePath/bhne")
            } else {
                ZipUtils.unzipFile(t?.path, "$filePath/bhne")
            }
            Log.e("filesLists===", fileList.toString());
            //var fileList = ZipUtil.unZipFolder(t?.path, "$filePath/bhne")
            var file = File("")
            var xiangmuName="";
            for (item: File in fileList) {
                if (item.name.contains(".xml")) {
                    file = item
                    xiangmuName=file.parentFile.name
                }
            }
            for (item: File in fileList) {
                if (!item.name.contains(".xml")){
                    //复制图片到指定的目录里面
                    //var copy=ZipUtil.copyFile(item.absolutePath, file.parentFile.absolutePath+"/"+item.name)
                }
            }
            for (item: File in fileList) {
                if (!item.name.contains(".xml")){
                    //删除掉bhne里面的图片
                    FileUtils.deleteFile(item)
                }
            }
            if (file.name == "") {
                ToastUtils.showShort("导入失败，ZIP包存在问题")
            } else {
                val xml = xmlFileToStr(file.absolutePath)
                ProgressDialogUtil.getInstence(context)?.progressDialogShow("正在导入文件，请稍后。。。")
                //createProgressDialog("正在导入文件，请稍后。。。")
                val threadPool = ThreadManager.getThreadPool()
                threadPool.execute {
                    Log.e("nameIcon==DB", file.absolutePath);
                    val success = ZipXmlUtils.parseXMLPull(t!!.name, xml, file.absolutePath, context,xiangmuName)
                    runOnUiThread {
                        if (!success) {
                            try {
                                FileUtils.deleteFile(file)
                                FileUtils.deleteDir("$filePath/bhne/${t.name.substring(0, t.name.length - 4)}")
                            } catch (e: Exception) {
                                Log.e("删除解压的ZIP文件失败，错误如下", e.message)
                                throw RuntimeException("删除解压的ZIP文件失败，错误如下")
                            }
                            ProgressDialogUtil.getInstence(context)?.progressDialogDismiss()
                            ToastUtils.showShort("导入失败,本地已存在该项目")
                        } else {
                            FileUtils.deleteFile(file)
                            //若工作完成，取消动画，初始化界面
                            ProgressDialogUtil.getInstence(context)?.progressDialogDismiss()
                            KeyboardUtils.hideSoftInput(context as Activity) //关闭软键盘
                            ToastUtils.showShort("导入成功")
                            (context as Activity).finish()
                        }
                    }
                }

            }
        })
    }


}